package top.tenebrous.termbor.rpc.loadbalance.randomWeight;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.tenebrous.termbor.rpc.loadbalance.ServiceLoadBalance;
import top.tenebrous.termbor.rpc.spi.SPIClass;

import java.util.List;
import java.util.Random;

/**
 * @program: termbor-rpc
 * @description:
 * @author: yazhang6
 * @create: 2024-05-24 14:20
 **/
@SPIClass
public class RandomWeightServiceLoadBalance<T> implements ServiceLoadBalance<T> {

    private final Logger logger = LoggerFactory.getLogger(RandomWeightServiceLoadBalance.class);

    @Override
    public T select(List<T> servers, int hashCode) {
       logger.info("基于加权随机算法的负载均衡策略...");
       if (servers == null || servers.isEmpty()) {
           return null;
       }
        hashCode = Math.abs(hashCode);
       int count = hashCode % servers.size();
       if (count <= 1) {
           count = servers.size();
       }
        Random random = new Random();
        int index = random.nextInt(count);
        return servers.get(index);
    }

}
